from flask import Blueprint, request, jsonify
from datetime import datetime
from warehouse_service import WarehouseService
from models import db, Product, Location, Batch

warehouse_bp = Blueprint('warehouse', __name__, url_prefix='/api/warehouse')

@warehouse_bp.route('/inventory/low-stock', methods=['GET'])
def get_low_stock():
    """库存预警接口"""
    threshold = request.args.get('threshold', type=int)
    products = WarehouseService.get_low_stock_products(threshold)
    return jsonify([{
        'product_id': p.id,
        'name': p.name,
        'barcode': p.barcode,
        'min_stock': p.min_stock,
        'current_stock': p.current_stock
    } for p in products])

@warehouse_bp.route('/products/search', methods=['GET'])
def search_products():
    """商品查询接口"""
    keyword = request.args.get('keyword')
    barcode = request.args.get('barcode')
    category = request.args.get('category')
    
    products = WarehouseService.search_products(keyword, barcode, category)
    return jsonify([{
        'id': p.id,
        'name': p.name,
        'barcode': p.barcode,
        'category': p.category,
        'purchase_price': p.purchase_price,
        'selling_price': p.selling_price
    } for p in products])

@warehouse_bp.route('/products/<int:product_id>/inventory', methods=['GET'])
def get_product_inventory(product_id):
    """获取商品库存详情"""
    inventory = WarehouseService.get_product_inventory(product_id)
    return jsonify([{
        'location_id': item.location_id,
        'location_code': item.location_code,
        'quantity': item.quantity
    } for item in inventory])

@warehouse_bp.route('/locations/usage', methods=['GET'])
def get_location_usage():
    """货位管理 - 获取货位使用情况"""
    locations = WarehouseService.get_location_usage()
    return jsonify([{
        'location_id': loc.id,
        'code': loc.code,
        'area': loc.area,
        'product_count': loc.product_count,
        'total_quantity': loc.total_quantity
    } for loc in locations])

@warehouse_bp.route('/batches/expiring', methods=['GET'])
def get_expiring_batches():
    """批次管理 - 获取即将过期的批次"""
    days = request.args.get('days', default=30, type=int)
    batches = WarehouseService.get_expiring_batches(days)
    return jsonify([{
        'id': b.id,
        'product_id': b.product_id,
        'product_name': b.product.name,
        'batch_number': b.batch_number,
        'expiry_date': b.expiry_date.strftime('%Y-%m-%d'),
        'quantity': b.quantity,
        'location_code': b.location.code if b.location else None
    } for b in batches])

@warehouse_bp.route('/batches', methods=['POST'])
def add_batch():
    """批次管理 - 添加新批次"""
    data = request.json
    try:
        production_date = datetime.strptime(data['production_date'], '%Y-%m-%d').date()
        expiry_date = datetime.strptime(data['expiry_date'], '%Y-%m-%d').date()
        
        batch = WarehouseService.add_batch(
            product_id=data['product_id'],
            batch_number=data['batch_number'],
            quantity=data['quantity'],
            production_date=production_date,
            expiry_date=expiry_date,
            supplier=data['supplier'],
            purchase_price=data['purchase_price'],
            location_id=data.get('location_id')
        )
        
        return jsonify({
            'id': batch.id,
            'message': '批次添加成功'
        }), 201
    except ValueError as e:
        return jsonify({'error': str(e)}), 400

@warehouse_bp.route('/inventory/move', methods=['POST'])
def move_inventory():
    """货位管理 - 移动库存"""
    data = request.json
    try:
        WarehouseService.move_inventory(
            product_id=data['product_id'],
            from_location_id=data['from_location_id'],
            to_location_id=data['to_location_id'],
            quantity=data['quantity']
        )
        return jsonify({'message': '库存移动成功'}), 200
    except ValueError as e:
        return jsonify({'error': str(e)}), 400
